package com.jackrain.nea.omslocal.util;


import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.omslocal.conf.LoadCloumnsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by chenyulu on 2017/4/20.
 */
@Slf4j
@Component
public class JsonKeyCheck {

    @Autowired
    private LoadCloumnsConfig loadCloumnsConfig;

    private Map insertcolsmap = LoadCloumnsConfig.insertcolsmap;

    private Map updatecolsmap = LoadCloumnsConfig.updatecolsmap;

    public JSONObject checkJsonkeycache(JSONObject jsonObj, String tablename, Map keyset) {

        String keys = (String) keyset.get(tablename);

        JSONObject jor = JSONObject.parseObject(jsonObj.toJSONString());

        Iterator it = jsonObj.keySet().iterator();

        while (it.hasNext()) {
            Object Key = it.next();
            String[] keylist = keys.split(",");
            boolean allStartsWithA =
                    Arrays.stream(keylist)
                            .anyMatch((s) -> s.startsWith(String.valueOf(Key).toLowerCase()));
            if (!allStartsWithA) {
                jor.remove(Key);
            } else {
                if (jsonObj.getString(Key.toString()).isEmpty()) {
                    jor.remove(Key);
                }
                if ("null".equals(jsonObj.get(Key))) {
                    jor.remove(Key);
                }

            }
        }
        return jor;
    }

    public JSONObject checkJsonkey(JSONObject jsonObj, String tablename, Map keyset) {

        String keys = (String) keyset.get(tablename);

        JSONObject jor = JSONObject.parseObject(jsonObj.toJSONString());

        Iterator it = jsonObj.keySet().iterator();

        while (it.hasNext()) {
            Object Key = it.next();
            String[] keylist = keys.split(",");
            boolean allStartsWithA =
                    Arrays.stream(keylist)
                            .anyMatch((s) -> s.equalsIgnoreCase(String.valueOf(Key)));
            if (!allStartsWithA) {
                jor.remove(Key);
            } else {
                if (jsonObj.getString(Key.toString()).isEmpty()) {
                    jor.remove(Key);
                }
                if ("null".equals(jsonObj.get(Key))) {
                    jor.remove(Key);
                }

            }
        }
        return jor;
    }



    public Map getInsertcolsmap() {
        return insertcolsmap;
    }

    public Map getUpdatecolsmap() {
        return updatecolsmap;
    }
}
